﻿using System.Windows.Forms;
using BrightIdeasSoftware;
using PictureOrganizer2.Database;
using System.Data.Linq;
using System.Linq;
using System.Data;
using System.Drawing;

namespace PictureOrganizer2.Forms
{
    public partial class TagConfigurationForm : Form
    {
        public TagConfigurationForm()
        {
            InitializeComponent();

            this.Icon = Icon.FromHandle(Images.tag_blue_edit.GetHicon());
            this.olvColumnCount.AspectGetter = new AspectGetterDelegate(delegate(object row)
            {
                int tagId = ((DatabaseDataSet.TagRow)((DataRowView)row).Row).ID;
                return (from cht in dbSet.ComicHasTag where cht.TagID == tagId select cht).Count();
            });

            this.tagTableAdapter.Fill(this.dbSet.Tag);
            this.comicHasTagTableAdapter.Fill(this.dbSet.ComicHasTag);
        }

        private void tsb_Add_Click(object sender, System.EventArgs e)
        {
            DatabaseDataSet.TagRow row = this.dbSet.Tag.NewTagRow();
            int nextId = (from t in dbSet.Tag orderby t.ID descending select t.ID).FirstOrDefault() + 1;
            row.ID = nextId;
            row.Name = "Neue Tag";
            this.dbSet.Tag.AddTagRow(row);
        }

        private void btn_Ok_Click(object sender, System.EventArgs e)
        {
            this.tagTableAdapter.Update(this.dbSet.Tag);
            this.comicHasTagTableAdapter.Update(this.dbSet.ComicHasTag);
        }

        private void dataListView_CellClick(object sender, CellClickEventArgs e)
        {
            if (this.dataListView.SelectedObject != null)
            {
                this.tsb_Delete.Enabled = true;
            }
            else
            {
                this.tsb_Delete.Enabled = false;
            }

        }

        private void tsb_Delete_Click(object sender, System.EventArgs e)
        {
            if (this.dataListView.SelectedObject != null)
            {
                DatabaseDataSet.TagRow row = (DatabaseDataSet.TagRow)((DataRowView)this.dataListView.SelectedObject).Row;
                
                foreach (var item in (from cht in dbSet.ComicHasTag where cht.TagID == row.ID select cht))
                {
                    item.Delete();
                }
                row.Delete();
            }
        }
    }
}
